package com.hengjun.baccarat.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import com.hengjun.baccarat.net.UrlConn;
import android.content.Context;

public class SocketConnection {
	public  Socket socket = null;
	public  Context context;
	public  boolean isclose=false;
	public  boolean isopen=true;
	private BufferedReader reader=null;
	private BufferedWriter writer =null;
	private boolean isrun=true;
	private ClientThread clientThread;
	
	
	public void connecttoserver(String socketData) throws UnknownHostException,
			IOException {
		if(socket==null){
			isrun=true;
			isopen=true;
			isclose=true;
		socket = RequestSocket(UrlConn.HOST, 16000);
		writer = new BufferedWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		 reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		SendMsg(socketData);
		clientThread=new ClientThread();
		clientThread.start();
		}
		

	}
	public  void isclosed(){
		while(isclose){
		
		}
	}
	
	public  void isOpened(){
		while(isopen){
		
		}
	}
	
	class ClientThread extends Thread {
		public void run() {
			try {
			
				while (isrun) {
					String txt = ReceiveMsg(socket);
					if (txt!=null&& txt.equals("0")) {
						 
						ThreadManager.handler.obtainMessage(0).sendToTarget();
						isclose=false;
						return;
					}
					if(txt!=null&&txt.equals("1")){
						isopen=false;
					}
					if(txt==null){
						close();
						//登出
						ThreadManager.handler.obtainMessage(500).sendToTarget();
						break;
					}
					
				}
			} catch (Exception e) {
				isclose=false;
				isopen=false;
				
				 close();
				e.printStackTrace();
			}
		}
	}

	private  Socket RequestSocket(String host, int port)
			throws UnknownHostException, IOException {
		Socket socket = new Socket(host, port);
		return socket;
	}

	private  void SendMsg(String msg) throws IOException {
		writer.write(msg.replace("\n", " ") + "\n");
		writer.flush();
	}

	private  String ReceiveMsg(Socket socket) throws IOException {
		String txt = reader.readLine();
		return txt;

	}
	

	public void close(){
		isrun=false;
		
		try {
			if(writer!=null){
				writer.close();
				writer=null;
			}
			if(reader!=null){
				reader.close();
				reader=null;
			}
			if(socket!=null){
				
				socket.close();
				socket=null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
